package top.oneit.jdownload.test.table;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.ContextMenuEvent;

import java.net.URL;
import java.util.ResourceBundle;

public class DownloadingTabController implements Initializable {
    @FXML
    private TableView downloadingTableView;
    @FXML
    private TableColumn title, size, surplus, speed, caozuo;


    @Override
    public void initialize(URL location, ResourceBundle resources) {
        initTableColumn();
        Button button = new Button("删除");
        Button button1 = new Button("删除");
        ObservableList<DownloadingTablePo> data =
                FXCollections.observableArrayList(
                        new DownloadingTablePo(0, new Label("Jacob"), "Smith", "Smith", "Smith", button),
                        new DownloadingTablePo(1, new Label("Jacob"), "Smith", "Smith", "Smith", button1)
                );

        // 对data操作即对表格操作，会同步更新的
        button.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                data.remove(0);// 删除第一列
            }
        });

        button1.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                DownloadingTablePo del=null;
                for (DownloadingTablePo po : data) {
                    if (po.getCaozuo() == button1) {
                        del=po;
                        break;
                    }
                }
                if (del!=null){
                    data.remove(del);
                }
            }
        });
        downloadingTableView.setItems(data);

        // 优先选择行时触发事件
        downloadingTableView.setOnContextMenuRequested(new EventHandler<ContextMenuEvent>() {
            @Override
            public void handle(ContextMenuEvent event) {
                // title 的类型为 Label
                data.get(0).getTitle().setText("1111");//更新第一列的title
                //downloadingTableView.refresh();//刷新表格
            }
        });
    }

    private void initTableColumn() {
        title.setCellValueFactory(new PropertyValueFactory<>("title"));
        size.setCellValueFactory(new PropertyValueFactory<>("size"));
        surplus.setCellValueFactory(new PropertyValueFactory<>("surplus"));
        speed.setCellValueFactory(new PropertyValueFactory<>("speed"));
        caozuo.setCellValueFactory(new PropertyValueFactory<>("caozuo"));
    }
}
